package com.my.admin.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.admin.entity.User;
import com.my.admin.service.ShiroService;
import com.my.admin.service.UserService;
import com.my.admin.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ShiroServiceImpl implements ShiroService {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;

    private static final long TIMEOUT = TimeUnit.HOURS.toSeconds(2);

    @Override
    public User getUserByUsername(String username) {
        return userService.getOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public String createToken(Long id) {
        String token = UUID.randomUUID().toString();
        Map<String, Object> map = new HashMap<>(2);
        map.put("userId", id);
        redisUtil.hmset(token, map);
        redisUtil.expire(token, TIMEOUT);
        return token;
    }

    @Override
    public void updateToken(String token) {
        redisUtil.expire(token, TIMEOUT);
    }

    @Override
    public void logout(String token) {
        if(isToken(token)) {
            redisUtil.del(token);
        }
    }

    @Override
    public boolean isToken(String token) {
        return redisUtil.hasKey(token);
    }


    @Override
    public Map<Object, Object> getTokenInfo(String token) {
        return redisUtil.hmget(token);
    }

}
